/* 初始化管理员账号
 * @Author: Leil
 * @Date: 2018-08-20 09:45:08 
 * @Last Modified by: Leil
 * @Last Modified time: 2018-08-20 23:46:05
 */
const readline = require('readline')
const sha1 = require('sha1')
const config = require('config-lite')(__dirname)
const Mongolass = require('mongolass')
const mongolass = new Mongolass(config.mongodb)

const Admin = mongolass.model('Admin', {
    name: {type: 'string', required: true},
    password: {type: 'string', required: true}
})

const name = 'admin'

// 从控制台获取输入密码
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})

// 初始化管理员信息
async function initAdminUser() {
    let password = await getConsolePwd()
    let user = await getAdminUser()
    console.log(user)
    if (user) {
        Admin
            .updateOne({name: name}, {$set: {password: password}})
            .exec()
            .then(() => {
                console.log('更新密码成功')
            })
    } else {
        Admin
            .insertOne({name: name, password: password})
            .exec()
            .then(() => {
                console.log('初始设置管理员密码成功')
            })
    }
}

// 从控制台获取输入密码
async function getConsolePwd() {
    let getPwd = new Promise((resolve, reject) => {
        rl.question('请输入管理员初始密码: ', (pwd) => {
            // 如果没有输入密码，设置初始密码admin
            let password = pwd ? pwd : 'admin'
            password = sha1(password)   // 加密
            rl.close()
            return resolve(password)
            })
    })
    let password = await getPwd
    return password
}

// 从数据库中获取管理员用户
async function getAdminUser() {
    let user = await Admin.findOne({name: name}).exec()
    return user
}

initAdminUser()

